package com.lxl.commons.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * @author 北上寻海
 */

public class VerifyCodeUtil   {
    final static int LINE_COUNT = 8;

    public static String getVerifyCode(int size){
        String str="1234567890QWERTYUIOPLKJHGFDSAZXCVBNMqwertyuioplkjhgfddsazxcvbnm";
        StringBuilder verifyCode= new StringBuilder();
        Random r = new Random();
        for(int i= 0;i<size;i++){
            char  c = str.charAt(r.nextInt(str.length()));
            verifyCode.append(c);
        }
        return verifyCode.toString();
    }


        public static void outputImage(OutputStream os,String verifyCode) throws IOException {

            //创建空白图片  TYPE_INT_RGB 表示具有8位RGB颜色分量的整数像素的图像
            BufferedImage image = new BufferedImage(100,30,BufferedImage.TYPE_INT_RGB);

            //获取图片画笔   此方法返回一个Graphics2D ，但这里是向后兼容性(保证与以前的标准或版本兼容的特性)。
            Graphics g = image.getGraphics();
            Random r = new Random();
            //设置画笔颜色  可以通过Color类中的预定义颜色来设置，也可以通过指定RGB值来设置。
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
            //绘制矩形背景
            g.fillRect(0, 0, 100, 30);
            //绘制8条干扰线
            for (int i = 0; i < LINE_COUNT; i++) {
                g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
                g.drawLine(r.nextInt(100), r.nextInt(30), r.nextInt(100), r.nextInt(30));
            }


            //设置字体样式
            g.setFont(new Font(null, Font.ITALIC + Font.BOLD, 24));
            char[] chars = verifyCode.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                //设置画笔颜色
                g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
                verifyCode = "" + chars[i];
                g.drawString(verifyCode, 15 + 20 * i, 25);

            }
            g.dispose();
            ImageIO.write(image, "jpg",os );
        }

}
